package com.gitee.huanminabc.jcommon.multithreading;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Description:
 * @Author huanmin
 * @Date 2024/6/5 下午1:01
 */
public interface LockKey<T> {

    /**
     * 加写锁, 读锁和写锁互斥, 意思就是在写锁的时候,不能加读锁,但是可以加写锁
     */
    void lock(T key);


    /**
     * 尝试加锁 不阻塞
     */
    boolean tryLock(T key);


    /**
     * 尝试加锁 阻塞 ,如果在指定时间内未获取到锁则返回false
     *
     * @param key     锁的唯一标识
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return 是否加锁成功
     */
    boolean tryLock(T key, long timeout, TimeUnit unit);


    /**
     * 解锁
     */
    void unlock(T key);




    default void lock(T key, Runnable runnable) {
        lock(key);
        try {
            runnable.run();
        } finally {
            unlock(key);
        }
    }

    default T lock(T key, Supplier<T> supplier) {
        lock(key);
        try {
            return supplier.get();
        } finally {
            unlock(key);
        }
    }

    default boolean tryLock(T key, Runnable runnable) {
        if (tryLock(key)) {
            try {
                runnable.run();
                return true;
            } finally {
                unlock(key);
            }
        }
        return false;
    }

    default T tryLock(T key, T failResult, Supplier<T> supplier) {
        if (tryLock(key)) {
            try {
                return supplier.get();
            } finally {
                unlock(key);
            }
        }
        return failResult;
    }

    //时间
    default boolean tryLock(T key, long timeout, TimeUnit unit, Runnable runnable) {
        if (tryLock(key, timeout, unit)) {
            try {
                runnable.run();
                return true;
            } finally {
                unlock(key);
            }
        }
        return false;
    }

    default T tryLock(T key, long timeout, TimeUnit unit, T failResult, Supplier<T> supplier) {
        if (tryLock(key, timeout, unit)) {
            try {
                return supplier.get();
            } finally {
                unlock(key);
            }
        }
        return failResult;
    }



}
